#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

int size =  sizeof(struct sockaddr_in);
int conect_sk;
//线程回调函数
void * func(void * arg)
{
    char * J_senmsg = calloc(1,128);
    while(1)
    {
        printf("Jack 请输入要回复的信息：\n");
        fgets(J_senmsg, 128 , stdin );

        int ret =  send(conect_sk, J_senmsg , strlen(J_senmsg), 0 );
        if(ret == -1)
        {
            perror("jack发送失败\n");
            break;
        }
        else
        {
            printf("jack成功发送信息:%s\n",J_senmsg);
        }
    }
    
    
}

int main(int argc, char const *argv[])
{
    
    //购买手机（创建网络编程接口）
    int sockfd = socket( AF_INET, SOCK_STREAM , 0);
    if(sockfd == -1)
    {
        perror("socket  faile\n");
        return -1;
    }
    
    //买电话卡（个人IP以及端口号的设置）

    // struct sockaddr_in {
    // sa_family_t     sin_family;     /* AF_INET */
    // in_port_t       sin_port;       /* Port number */
    // struct in_addr  sin_addr;       /* IPv4 address */
    // };
    struct sockaddr_in my_addr = {0};
    my_addr.sin_family = AF_INET;
    my_addr.sin_addr.s_addr = inet_addr("127.0.0.1" );
    my_addr.sin_port = htons(65001);


    //绑定手机和电话卡
    int ret = bind(sockfd, (struct sockaddr *)&my_addr,size); //如果成功则返回一个新的待连接字
    if(ret == -1)
    {
        perror("bind faile\n");
        return -1;
    }
    else
    {
        printf("绑定成功\n");
    }


    //设置监听
    if(listen(sockfd, 4))
    {
        perror("listen faile\n");
        return -1;
    }
    else
    {
        printf("监听成功\n");
    }

    //等待连接
    struct sockaddr_in from_addr;
    conect_sk =  accept(sockfd , (struct sockaddr *)&from_addr,&size);  //如果成功就返回一个新的已连接字,会阻塞等待，如果没有人连接就会一直等待，程序会一直卡在这里
    if(conect_sk == -1)
    {
        perror("conect faile\n");
        return -1;
    }
    else
    {
        printf("连接成功\n");
    }

    //创建线程用来发送信息
    pthread_t thread;
    int m = pthread_create(&thread, NULL , func , NULL);
    if(m)
    {
        perror("ptread error\n");
    }
    else
    {
        printf("发送信息线程创建成功\n");
    }


    //坐等对方电话打来
    char * rev_msg = calloc(1,1024);

    while(1)
    {   
        
        printf("等待Rose发来消息...\n");

        int ret = recv(conect_sk, rev_msg, 128 , 0);

        if(ret == -1)
        {
            perror("recive faile\n");
            return -1;
        }
        else
        {
            printf("recive byte :%d msg:%s\n",ret,rev_msg);
        }

    }


    //关闭套接字
    close(sockfd);

    return 0;
}
